//
//  LocalViewController.m
//  KiklinkApp
//
//  Created by LJC on 14-9-2.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "LocalViewController.h"

#import "ImagesManager.h"
#import "UIView+loadWithNib.h"
#import "UIColor+hex.h"

#import "SearchBar.h"
#import "LocalCell.h"
#import "MJRefresh.h"

#import "FilterViewController.h"
#import "SearchViewController.h"
#import "ProductViewController.h"

#import "API.h"

static NSString *LocalTableCellIdentifier1 = @"LocalCell";
static NSString *LocalTableCellIdentifier2 = @"LocalCell";
static NSString *LocalTableCellIdentifier3 = @"LocalCell";

@interface LocalViewController ()
{
    //data
    NSMutableArray *localTableArray1;
    NSMutableArray *localTableArray2;
    NSMutableArray *localTableArray3;
    NSInteger page1;
    NSInteger page2;
    NSInteger page3;
    NSInteger totalPage1;
    NSInteger totalPage2;
    NSInteger totalPage3;
    
    //ui
    UIBarButtonItem *searchItem;
    SearchBar *search;
    UIBarButtonItem *searchBarItem;
    UIButton *filterButton;
}
@end

@implementation LocalViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"附近";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];

    
    //loading
    [self.activity1 startAnimating];
    [self.activity2 startAnimating];
    [self.activity3 startAnimating];
    self.refreshBtn1.hidden = YES;
    self.refreshBtn2.hidden = YES;
    self.refreshBtn3.hidden = YES;
    [self.refreshBtn1 addTarget:self action:@selector(refresh1) forControlEvents:UIControlEventTouchUpInside];
    [self.refreshBtn2 addTarget:self action:@selector(refresh2) forControlEvents:UIControlEventTouchUpInside];
    [self.refreshBtn3 addTarget:self action:@selector(refresh3) forControlEvents:UIControlEventTouchUpInside];
    
    
    //BundleImages
    ImagesManager *imagesManager = [ImagesManager sharedImagesManager];
    
    
    //leftNavItem
    filterButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [filterButton setFrame:CGRectMake(0, 0, NavBarHeight/2.4, NavBarHeight/2.5)];
    [filterButton setBackgroundImage:[imagesManager filter] forState:UIControlStateNormal];
    [filterButton setBackgroundImage:[imagesManager filterTapped] forState:UIControlStateHighlighted];
    [filterButton addTarget:self action:@selector(filter) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftNavBarItem = [[UIBarButtonItem alloc] initWithCustomView:filterButton];
    self.navigationItem.leftBarButtonItem = leftNavBarItem;
    
    
    //rightNavItem
    searchItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBarPresent)];
    searchItem.tintColor = [UIColor colorWithHexString:AppColor_Main andAlpha:0.8];
    
    search = [[SearchBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth*9/10, NavBarHeight)];
    search.placeholder = @"向右滑动取消";
    search.delegate = self;
    UISwipeGestureRecognizer *rightSwip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(searchBarDismis)];
    rightSwip.direction = UISwipeGestureRecognizerDirectionRight;
    [search addGestureRecognizer:rightSwip];
    searchBarItem = [[UIBarButtonItem alloc] initWithCustomView:search];
    
    self.navigationItem.rightBarButtonItem = searchItem;
    
    
    //segment
    self.segment.selectedSegmentIndex = 0;
    self.segment.tintColor = [UIColor colorWithHexString:AppColor_Main];
    [self.segment addTarget:self action:@selector(segmentAction) forControlEvents:UIControlEventValueChanged];
    
    
    //localTable
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self.localTable2 setSeparatorInset:UIEdgeInsetsZero];
    self.localTable2.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.localTable2.separatorColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.localTable2.delegate = self;
    self.localTable2.dataSource = self;
    [self.localTable2 registerClass:[UITableViewCell class] forCellReuseIdentifier:LocalTableCellIdentifier2];
    [self.localTable2 reloadData];
    
    [self.localTable1 setSeparatorInset:UIEdgeInsetsZero];
    self.localTable1.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.localTable1.separatorColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.localTable1.delegate = self;
    self.localTable1.dataSource = self;
    [self.localTable1 registerClass:[UITableViewCell class] forCellReuseIdentifier:LocalTableCellIdentifier1];
    [self.localTable1 reloadData];

    [self.localTable3 setSeparatorInset:UIEdgeInsetsZero];
    self.localTable3.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.localTable3.separatorColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.localTable3.delegate = self;
    self.localTable3.dataSource = self;
    [self.localTable3 registerClass:[UITableViewCell class] forCellReuseIdentifier:LocalTableCellIdentifier3];
    [self.localTable3 reloadData];

    [self setupRefresh];
    
    //data
    localTableArray1 = [[NSMutableArray alloc] init];
    localTableArray2 = [[NSMutableArray alloc] init];
    localTableArray3 = [[NSMutableArray alloc] init];
    page1 = 1;
    page2 = 1;
    page3 = 1;
    [self getData:1 Condition:@"first" SortStyle:@""];
    [self getData:1 Condition:@"first" SortStyle:@"price"];
    [self getData:1 Condition:@"first" SortStyle:@"buyedCount desc"];
}

#pragma mark - get data
//condition:first&header&footer  sortStyle:price&buyedCount desc
- (void)getData:(NSInteger)pageNum Condition:(NSString *)condition SortStyle:(NSString *)sortStyle
{
    NSLog(@"page:%ld",(long)pageNum);
    [API courseSearchWithKeyword:@"" distance:@0 tags:@"" category:@0 sortStyle:sortStyle pageNumber:[NSNumber numberWithInteger:pageNum] Callback:^(int stateCode, NSString *word, id content) {
            
        if (stateCode == SUCCESS) {
            ProductPage *productPage = (ProductPage *)content;
            NSMutableArray *result = [[NSMutableArray alloc] initWithArray:productPage.result];
            
            if ([sortStyle isEqualToString:@""]) {
                
                if ([condition isEqualToString:@"first"]) {
                    totalPage1 = productPage.lastPageNumber;
                    self.localTable1.scrollEnabled = YES;
                    page1 = 2;
                    localTableArray1 = result;
                } else if ([condition isEqualToString:@"header"]) {
                    page1 = 2;
                    localTableArray1 = result;
                } else if ([condition isEqualToString:@"footer"]) {
                    page1 ++;
                    [localTableArray1 addObjectsFromArray:result];
                }
                
                [self loadData1:condition];
                
            } else if ([sortStyle isEqualToString:@"price"]) {
                
                if ([condition isEqualToString:@"first"]) {
                    totalPage2 = productPage.lastPageNumber;
                    self.localTable2.scrollEnabled = YES;
                    page2 = 2;
                    localTableArray2 = result;
                } else if ([condition isEqualToString:@"header"]) {
                    page2 = 2;
                    localTableArray2 = result;
                } else if ([condition isEqualToString:@"footer"]) {
                    page2 ++;
                    [localTableArray2 addObjectsFromArray:result];
                }
                
                [self loadData2:condition];
                
            } else if ([sortStyle isEqualToString:@"buyedCount desc"]) {
                
                if ([condition isEqualToString:@"first"]) {
                    totalPage3 = productPage.lastPageNumber;
                    self.localTable3.scrollEnabled = YES;
                    page3 = 2;
                    localTableArray3 = result;
                } else if ([condition isEqualToString:@"header"]) {
                    page3 = 2;
                    localTableArray3 = result;
                } else if ([condition isEqualToString:@"footer"]) {
                    page3 ++;
                    [localTableArray3 addObjectsFromArray:result];
                }
                
                [self loadData3:condition];
                
            }
        } else {
            
            if ([sortStyle isEqualToString:@""]) {
                
                if ([condition isEqualToString:@"first"]) {
                    self.localTable1.scrollEnabled = NO;
                    [self.activity1 stopAnimating];
                    self.refreshBtn1.hidden = NO;
                } else if ([condition isEqualToString:@"header"]) {
                    [self.localTable1 headerEndRefreshing];
                } else if ([condition isEqualToString:@"footer"]) {
                    [self.localTable1 footerEndRefreshing];
                }
                
            } else if ([sortStyle isEqualToString:@"price"]) {
                
                if ([condition isEqualToString:@"first"]) {
                    self.localTable2.scrollEnabled = NO;
                    [self.activity2 stopAnimating];
                    self.refreshBtn2.hidden = NO;
                } else if ([condition isEqualToString:@"header"]) {
                    [self.localTable2 headerEndRefreshing];
                } else if ([condition isEqualToString:@"footer"]) {
                    [self.localTable2 footerEndRefreshing];
                }
                
            } else if ([sortStyle isEqualToString:@"buyedCount desc"]) {
                
                if ([condition isEqualToString:@"first"]) {
                    self.localTable3.scrollEnabled = NO;
                    [self.activity3 stopAnimating];
                    self.refreshBtn3.hidden = NO;
                } else if ([condition isEqualToString:@"header"]) {
                    [self.localTable3 headerEndRefreshing];
                } else if ([condition isEqualToString:@"footer"]) {
                    [self.localTable3 footerEndRefreshing];
                }
                
            }
            
        }
        
    }];
}

- (void)loadData1:(NSString *)condition
{
    [self.localTable1 reloadData];
    
    if ([condition isEqualToString:@"first"]) {
        [self.activity1 stopAnimating];
    } else if ([condition isEqualToString:@"header"]) {
        [self.localTable1 headerEndRefreshing];
    } else if ([condition isEqualToString:@"footer"]) {
        [self.localTable1 footerEndRefreshing];
    }
    
    self.localTable1.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}
- (void)loadData2:(NSString *)condition
{
    [self.localTable2 reloadData];
    
    if ([condition isEqualToString:@"first"]) {
        [self.activity2 stopAnimating];
    } else if ([condition isEqualToString:@"header"]) {
        [self.localTable2 headerEndRefreshing];
    } else if ([condition isEqualToString:@"footer"]) {
        [self.localTable2 footerEndRefreshing];
    }
    
    self.localTable2.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}
- (void)loadData3:(NSString *)condition
{
    [self.localTable3 reloadData];
    
    if ([condition isEqualToString:@"first"]) {
        [self.activity3 stopAnimating];
    } else if ([condition isEqualToString:@"header"]) {
        [self.localTable3 headerEndRefreshing];
    } else if ([condition isEqualToString:@"footer"]) {
        [self.localTable3 footerEndRefreshing];
    }
    
    self.localTable3.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}

- (void)refresh1
{
    self.refreshBtn1.hidden = YES;
    [self.activity1 startAnimating];
    
    [self getData:1 Condition:@"first" SortStyle:@""];
}
- (void)refresh2
{
    self.refreshBtn2.hidden = YES;
    [self.activity2 startAnimating];
    
    [self getData:1 Condition:@"first" SortStyle:@"price"];
}
- (void)refresh3
{
    self.refreshBtn3.hidden = YES;
    [self.activity3 startAnimating];
    
    [self getData:1 Condition:@"first" SortStyle:@"buyedCount desc"];
}
#pragma mark - get data End

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    
    self.title = @"附近";
    [filterButton setHidden:NO];
    [search resignFirstResponder];
    self.navigationItem.rightBarButtonItem = searchItem;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - searchBarPresent&dismiss&input
- (void)searchBarPresent
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.3;
    animation.type = @"push";
    animation.subtype = @"fromRight";
    
    self.title = @"";
    [filterButton setHidden:YES];
    self.navigationItem.rightBarButtonItem = searchBarItem;
    
    [self.navigationController.navigationBar.layer addAnimation:animation forKey:nil];
    [search becomeFirstResponder];
}
- (void)searchBarDismis
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.4;
    animation.type = @"push";
    animation.subtype = @"fromLeft";
    
    self.title = @"附近";
    [filterButton setHidden:NO];
    [search resignFirstResponder];
    self.navigationItem.rightBarButtonItem = searchItem;
    
    [self.navigationController.navigationBar.layer addAnimation:animation forKey:nil];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.keyWord = searchBar.text;
    [self.navigationController pushViewController:searchVC animated:YES];
}
#pragma mark - searchBarPresent&dismiss&input End

#pragma mark - filterAction
- (void)filter
{
    FilterViewController *filterVC = [[FilterViewController alloc] init];
    [self.navigationController pushViewController:filterVC animated:YES];
}
#pragma mark - filterAction End

#pragma mark - segmentAction
- (void)segmentAction
{
    NSInteger selectedIndex = self.segment.selectedSegmentIndex;
    switch (selectedIndex) {
        case 0:
            [self.localTable1 setHidden:NO];
            [self.localTable2 setHidden:YES];
            [self.localTable3 setHidden:YES];
            
            [self.loadingView1 setHidden:NO];
            [self.loadingView2 setHidden:YES];
            [self.loadingView3 setHidden:YES];
            break;
        case 1:
            [self.localTable1 setHidden:YES];
            [self.localTable2 setHidden:NO];
            [self.localTable3 setHidden:YES];
            
            [self.loadingView1 setHidden:YES];
            [self.loadingView2 setHidden:NO];
            [self.loadingView3 setHidden:YES];
            break;
        case 2:
            [self.localTable1 setHidden:YES];
            [self.localTable2 setHidden:YES];
            [self.localTable3 setHidden:NO];
            
            [self.loadingView1 setHidden:YES];
            [self.loadingView2 setHidden:YES];
            [self.loadingView3 setHidden:NO];
            break;
        default:
            break;
    }
}
#pragma mark - segmentAction End

#pragma tableView dataSource&delegate  &MJRefresh
- (void)setupRefresh
{
    [self.localTable1 addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.localTable1 addFooterWithTarget:self action:@selector(footerRereshing)];
    self.localTable1.headerPullToRefreshText = @"下拉可以刷新";
    self.localTable1.headerReleaseToRefreshText = @"松开马上刷新";
    self.localTable1.headerRefreshingText = @"正在刷新...";
    self.localTable1.footerPullToRefreshText = @"上拉加载更多";
    self.localTable1.footerReleaseToRefreshText = @"松开马上加载";
    self.localTable1.footerRefreshingText = @"正在加载...";
    
    [self.localTable2 addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.localTable2 addFooterWithTarget:self action:@selector(footerRereshing)];
    self.localTable2.headerPullToRefreshText = @"下拉可以刷新";
    self.localTable2.headerReleaseToRefreshText = @"松开马上刷新";
    self.localTable2.headerRefreshingText = @"正在刷新...";
    self.localTable2.footerPullToRefreshText = @"上拉加载更多";
    self.localTable2.footerReleaseToRefreshText = @"松开马上加载";
    self.localTable2.footerRefreshingText = @"正在加载...";
    
    [self.localTable3 addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.localTable3 addFooterWithTarget:self action:@selector(footerRereshing)];
    self.localTable3.headerPullToRefreshText = @"下拉可以刷新";
    self.localTable3.headerReleaseToRefreshText = @"松开马上刷新";
    self.localTable3.headerRefreshingText = @"正在刷新...";
    self.localTable3.footerPullToRefreshText = @"上拉加载更多";
    self.localTable3.footerReleaseToRefreshText = @"松开马上加载";
    self.localTable3.footerRefreshingText = @"正在加载...";
}
- (void)headerRereshing
{
    //data
    if (self.segment.selectedSegmentIndex == 0) {
        [self getData:1 Condition:@"header" SortStyle:@""];
    } else if (self.segment.selectedSegmentIndex == 1) {
        [self getData:1 Condition:@"header" SortStyle:@"price"];
    } else if (self.segment.selectedSegmentIndex == 2) {
        [self getData:1 Condition:@"header" SortStyle:@"buyedCount desc"];
    }
}
- (void)footerRereshing
{
    //data
    if (self.segment.selectedSegmentIndex == 0) {
        if (page1 <= totalPage1) {
            [self getData:page1 Condition:@"footer" SortStyle:@""];
        } else {
            [self.localTable1 footerEndRefreshing];
        }
    } else if (self.segment.selectedSegmentIndex == 1) {
        if (page2 <= totalPage2) {
            [self getData:page2 Condition:@"footer" SortStyle:@"price"];
        } else {
            [self.localTable2 footerEndRefreshing];
        }
    } else if (self.segment.selectedSegmentIndex == 2) {
        if (page3 <= totalPage3) {
            [self getData:page3 Condition:@"footer" SortStyle:@"buyedCount desc"];
        } else {
            [self.localTable3 footerEndRefreshing];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.localTable1) {
        return localTableArray1.count;
    } else if (tableView == self.localTable2) {
        return localTableArray2.count;
    } else if (tableView == self.localTable3) {
        return localTableArray3.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.localTable1) {
        BOOL nibsRegistered = NO;
        if (!nibsRegistered) {
            UINib *nib = [UINib nibWithNibName:@"LocalCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:LocalTableCellIdentifier1];
            nibsRegistered = YES;
        }
        LocalCell *cell = (LocalCell *)[tableView dequeueReusableCellWithIdentifier:LocalTableCellIdentifier1];
        [cell loadDataWithProduct:[localTableArray1 objectAtIndex:indexPath.row]];
        return cell;
    } else if (tableView == self.localTable2) {
        BOOL nibsRegistered = NO;
        if (!nibsRegistered) {
            UINib *nib = [UINib nibWithNibName:@"LocalCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:LocalTableCellIdentifier2];
            nibsRegistered = YES;
        }
        LocalCell *cell = (LocalCell *)[tableView dequeueReusableCellWithIdentifier:LocalTableCellIdentifier2];
        [cell loadDataWithProduct:[localTableArray2 objectAtIndex:indexPath.row]];
        return cell;
    } else if (tableView == self.localTable3) {
        BOOL nibsRegistered = NO;
        if (!nibsRegistered) {
            UINib *nib = [UINib nibWithNibName:@"LocalCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:LocalTableCellIdentifier3];
            nibsRegistered = YES;
        }
        LocalCell *cell = (LocalCell *)[tableView dequeueReusableCellWithIdentifier:LocalTableCellIdentifier3];
        [cell loadDataWithProduct:[localTableArray3 objectAtIndex:indexPath.row]];
        return cell;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 96;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductViewController *productVC = [[ProductViewController alloc] init];
    Product *corProduct;
    
    if (tableView == self.localTable1) {
        corProduct = [localTableArray1 objectAtIndex:indexPath.row];
    } else if (tableView == self.localTable2) {
        corProduct = [localTableArray2 objectAtIndex:indexPath.row];
    } else if (tableView == self.localTable3) {
        corProduct = [localTableArray3 objectAtIndex:indexPath.row];
    }
    
    productVC.productID = corProduct.id;
    productVC.product = corProduct;
    [self.navigationController pushViewController:productVC animated:YES];
}
#pragma tableView dataSource&delegate End

@end
